<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
		<link rel="stylesheet" href="/css/main.css"/>
		<script>
			var api_url = 'https://www.googleapis.com/urlshortener/v1/url';
			var api_key = 'AIzaSyDVOwcSxoH5oU9bp2RLyY0fkInYbUoU2LQ';

			init = function() {
				document.getElementById('headline').innerText = chrome.i18n.getMessage('headline');
				document.getElementById('label_urls').innerText = chrome.i18n.getMessage('tabs') + ':';
				document.getElementById('label_url').innerText = chrome.i18n.getMessage('url') + ':';
				document.getElementById('url').placeholder = chrome.i18n.getMessage('url_example');
				document.getElementById('button_submit').value = chrome.i18n.getMessage('shorten');
				document.getElementById('short_url').style.width = String(chrome.i18n.getMessage('short_url_width')) + 'px';
				document.getElementById('label_short_url').innerText = chrome.i18n.getMessage('short_url') + ':';
				document.getElementById('copy_short_url').value = chrome.i18n.getMessage('copy');
				document.getElementById('test_short_url').value = chrome.i18n.getMessage('test');

				urlsSelect();

				chrome.windows.getCurrent(function(w) {
					wid = w.id;
					chrome.tabs.getSelected(wid, function(t) {
						if (t.url.substr(0, 7) == 'http://' || t.url.substr(0, 8) == 'https://') {
							document.getElementById('url').value = t.url;
							getHeaders();
						}
					});
				});

				document.getElementById('urls').addEventListener('change', function(event) {
					document.getElementById('url').value = this.value;
					this.selectedIndex = 0;
					clearError();
					getHeaders();
				}, false);

				document.getElementById('url').addEventListener('keyup', function(event) {
					if (event.keyCode != 13) {
						document.getElementById('result').style.display = 'none';
						clearError();
					}
				}, false);

				delete init;
			}

			isValidUrl = function(url) {
				if (url.substr(0, 7) == 'http://' || url.substr(0, 8) == 'https://') {
					return true;
				} else {
					return false;
				}				
			}

			urlsSelect = function() {
				chrome.windows.getAll({'populate': true}, function(windows) {
					windows.forEach(function(w) {
						w.tabs.forEach(function(t) {
							if (isValidUrl(t.url) == true) {
								document.getElementById('urls').innerHTML += '<option>'+String(t.url)+'</option>';
							}
						});
					});
				});
			}

			showError = function(type, message) {
				document.getElementById('loading').style.display = 'none';
				document.getElementById('loading').value = 0;
				document.getElementById('result').style.display = 'none';
				document.getElementById('result').innerText = '';
				document.getElementById('error').innerText = chrome.i18n.getMessage(type);
				if (message != '') {
					document.getElementById('error').innerText += ' ('+String(message)+')';
				}
				document.getElementById('error').style.backgroundImage = 'url(/images/'+type+'.png)';
				document.getElementById('error').style.display = 'block';
			}

			clearError = function() {
				document.getElementById('error').style.display = 'none';
				document.getElementById('error').innerText = '';
			}

			copyValue = function(id) {
				document.getElementById(id).select();
				document.execCommand('Copy');
				window.getSelection().removeAllRanges();
			}

			openLink = function(url) {
				switch (window.localStorage.getItem('link_target')) {
					case null:
					case undefined:
					case 'new_tab':
						chrome.tabs.create({'url': url});
						break;
					case 'active_tab':
						chrome.windows.getCurrent(function(w) {
							wid = w.id;
							chrome.tabs.getSelected(wid, function(t) {
								tid = t.id;
								chrome.tabs.update(tid, {'url': url});
							});
						});
						break;
					case 'new_window':
						chrome.windows.create({'url': url});
						break;
				}

				window.close();
			}
			
			getShortUrl = function() {
				clearError();

				document.getElementById('result').style.display = 'none';
				document.getElementById('short_url').value = '';

				var url = document.getElementById('url').value;

				if (url != '') {
					if (isValidUrl(url) == true) {
						document.getElementById('loading').style.display = 'block';
						var data = '{"longUrl": "'+document.getElementById('url').value+'"}';
						var xhr = new XMLHttpRequest();
						xhr.open('POST', api_url+'?key='+api_key, true);
						xhr.setRequestHeader('Content-Type', 'application/json');
						xhr.onreadystatechange = function() {
							document.getElementById('loading').value = xhr.readyState;
							if (xhr.readyState == 4) {
								document.getElementById('loading').value = xhr.readyState;
								document.getElementById('loading').style.display = 'none';
								document.getElementById('loading').value = 0;
								if (xhr.getAllResponseHeaders() != '') {
									var response = JSON.parse(xhr.responseText);
									if (response.error == undefined) {
										document.getElementById('short_url').value = response.id;
										document.getElementById('result').style.display = 'block';
									} else {
										showError('general_error', response.error.message);
									}
								} else {
									showError('network_error', '');
								}
							}
						}
						xhr.send(data);
					} else {
						showError('url_not_valid', '');
					}
				}
			}
		</script>
	</head>
	<body onload="init()">
		<h1 id="headline"></h1>
		<form id="form_url" onsubmit="getShortUrl(); return false;">
			<p>
				<label for="urls" id="label_urls"></label>
				<select id="urls"/>
					<option></option>
				</select>
			</p>
			<p>
				<label for="url" id="label_url"></label>
				<input type="text" id="url"/>
			</p>
			<p>
				<label>&nbsp;</label>			
				<input type="submit" id="button_submit"/>
			</p>
		</form>
		<progress id="loading" value="0" max="4"></progress>
		<form id="result">
			<p>
				<label for="short_url" id="label_short_url"></label>
				<input type="text" id="short_url" readonly="readonly"/>
				<input type="button" id="copy_short_url" onclick="copyValue('short_url')"/>
				<input type="button" id="test_short_url" onclick="openLink(document.getElementById('short_url').value)"/>
			</p>
		</form>
		<div id="error"></div>
	</body>
</html>